import { INestApplication } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { Test, TestingModule } from '@nestjs/testing'
import supertest from 'supertest'
import { AppModule } from '../src/app.module'

describe('App', () => {
  let app: INestApplication
  let prefix: string

  const prefixUrl = (url: string) => prefix + url

  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [AppModule]
    }).compile()

    app = module.createNestApplication()
    const config = app.get(ConfigService)

    prefix = config.get('prefix')

    app.setGlobalPrefix(prefix)

    await app.init()
  })

  afterAll(async () => {
    await app.close()
  })

  describe('AuthController', () => {
    describe('POST /auth/signin', () => {
      it('should signin success', done => {
        supertest(app.getHttpServer())
          .post(prefixUrl('/auth/signin'))
          .send({ username: 'admin', password: '123456' })
          .expect(201, done)
      })

      it('should sigin fail', done => {
        supertest(app.getHttpServer())
          .post(prefixUrl('/auth/signin'))
          .send({ username: 'admin', password: '111111' })
          .expect(400, done)
      })
    })
  })

  describe('UserController', () => {
    let token: string = 'Bearer '

    beforeAll(done => {
      supertest(app.getHttpServer())
        .post(prefixUrl('/auth/signin'))
        .send({ username: 'admin', password: '123456' })
        .then(resp => {
          token += resp.body.data
          done()
        })
    })

    describe('GET /user/one', () => {
      it('should get one fail', done => {
        supertest(app.getHttpServer())
          .get(prefixUrl('/user/one'))
          .set('Authorization', token)
          .expect(200, done)
      })
    })
  })
})
